import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyJwtToken } from './lib/auth/jwt'

// 需要身份验证的路径
const protectedPaths = [
  '/profile',
  '/change-password',
  '/cabinet',
  '/api/cabinet/save',
]

// 统计请求计数器
let statisticsRequestCount = 0

export function middleware(request: NextRequest) {
  const path = request.nextUrl.pathname
  
  // 监控统计请求
  if (path === '/hybridaction/zybTrackerStatisticsAction') {
    statisticsRequestCount++
    console.log(`[Statistics] Request count: ${statisticsRequestCount}, Timestamp: ${new Date().toISOString()}`)
    return NextResponse.next()
  }
  
  // 检查路径是否需要身份验证
  const isProtectedPath = protectedPaths.some(protectedPath => 
    path === protectedPath || path.startsWith(`${protectedPath}/`)
  )
  
  // 如果不是受保护的路径，直接放行
  if (!isProtectedPath) {
    return NextResponse.next()
  }
  
  // 获取令牌
  const authHeader = request.headers.get('authorization')
  const token = authHeader && authHeader.startsWith('Bearer ') 
    ? authHeader.split(' ')[1] 
    : null
  
  // 如果是API请求，验证令牌
  if (path.startsWith('/api/')) {
    if (!token) {
      return NextResponse.json(
        { success: false, error: '未授权访问' },
        { status: 401 }
      )
    }
    
    const payload = verifyJwtToken(token)
    if (!payload) {
      return NextResponse.json(
        { success: false, error: '无效的令牌' },
        { status: 401 }
      )
    }
    
    return NextResponse.next()
  }
  
  // 如果是页面请求，检查Cookie中的令牌
  const isLoggedIn = request.cookies.get('isLoggedIn')?.value === 'true'
  
  if (!isLoggedIn) {
    // 重定向到登录页面
    const url = new URL('/login', request.url)
    url.searchParams.set('callbackUrl', encodeURI(request.url))
    return NextResponse.redirect(url)
  }
  
  return NextResponse.next()
} 